<template>
    <div class="">
        <div style="margin: 15px 0">
                <a-space>
                    <a-select v-model:value="searchForm.field_name" style="width: 100px" :options="searchFieldOptions"></a-select>
                    <a-textarea v-model:value="searchForm.field_value" :rows="1" style="width: 300px" placeholder="多个换行"></a-textarea>
                    <a-button type="primary" @click="fn_search" style="margin-right: 20px; width: 120px"> 搜索 </a-button>
                    <a-button type="primary" @click="modal_add_visible = true" style="margin-right: 20px; width: 120px"> 添加 </a-button>
                    <!-- <a-button type="primary" @click="modal_edit_visible = true" style="margin-right: 20px; width: 120px"> 修改 </a-button> -->
                    <a-button danger @click="modal_visible = true" style="margin-right: 20px; width: 120px"> 删除 </a-button>
                    
                </a-space>
            </div>
            <a-modal v-model:open="modal_visible" title="删除" @ok="handleOk">
                <p>请确认删除选中的数据？</p>
            </a-modal>
            <a-modal v-model:open="modal_add_visible" title="添加" @ok="addOk">
                <a-form-item label="type" :label-col="{span:2, offset: 3 }">
                    <a-input v-model:value="addData.type"></a-input>
                </a-form-item>
                <a-form-item label="url" :label-col="{span:2, offset: 3 }">
                    <a-input v-model:value="addData.url"></a-input>
                </a-form-item>
                <a-form-item label="domain" :label-col="{span:3, offset: 2 }">
                    <a-input v-model:value="addData.domain"></a-input>
                </a-form-item>
                <a-form-item label="func_position" :label-col="{span:5, offset: 0 }">
                    <a-input v-model:value="addData.func_position"></a-input>
                </a-form-item>
            </a-modal>
            <a-modal v-model:open="modal_edit_visible" title="修改" @ok="editOk">
                <a-form-item label="func_position" :label-col="{span:5, offset: 0 }">
                    <a-input v-model:value="editData.func_position"></a-input>
                </a-form-item>
            </a-modal>

        <a-spin :spinning="tableLoading" style="margin-top: 15px">
                <a-table
                    sticky
                    :row-selection="rowSelection"
                    :rowKey="(row: any) => JSON.stringify(row)"
                    :columns="columns"
                    :data-source="tableData"
                    :scroll="{ x: 1800,y: 500 }"
                    bordered
                    :pagination="false"
                    size="small"
                    @change="handleTableChange"
                    class="table"
                >
                </a-table>
            </a-spin>
            <a-row justify="center" v-if="pagePotions.total > 10" style="margin-top: 10px">
                <a-pagination
                    v-model:current="pagePotions.page"
                    v-model:pageSize="pagePotions.size"
                    show-quick-jumper
                    showSizeChanger
                    :total="pagePotions.total"
                    :page-size-options="pagePotions.pageSizeOptions"
                    @change="pageChange"
                    :show-total="(total: number) => `总计 ${total} 项`"
                />
            </a-row>
    </div>
    </template>
    
    <script lang="ts" setup>
    import {getMaterial,deltetMaterial,addMaterial,editMaterial} from "@/api/externalLinks";
    import { Tag, type TableColumnsType, Button, Popconfirm, Space, message, type MenuProps } from "ant-design-vue";
    import {inject} from "vue";
    const tableLoading = ref(false);
    const tableData = ref([]);
    const modal_visible = ref(false);
    const modal_add_visible = ref(false);
    const modal_edit_visible = ref(false);
    
    // 选择的行
    const selectedRowKeys = inject("MaterialSelectedRowKeys",ref<Array<number>>([]));
    // 行Key
    const rowSelection = ref<any>({
        checkStrictly: false,
        onSelect: (_: boolean, __: boolean, selectedRows: Array<Record<string, any>>) => {
            selectedRowKeys.value = selectedRows.map((item) => item.id);
        },
        onSelectAll: (_: boolean, __: boolean, selectedRows: Array<Record<string, any>>) => {
            selectedRowKeys.value = selectedRows.map((item) => item.id);
        }
    });
    const columns: TableColumnsType = [
        {
            title: "id",
            dataIndex: "id",
            fixed: "left",
            align: "center",
            key: "id",
            sorter: true,
            width: 40
        },
        {
            title: "domain",
            dataIndex: "domain",
            align: "center",
            key: "domain",
            width: 150
        },
        {
            title: "url",
            dataIndex: "url",
            align: "center",
            key: "url",
            width: 250
        },
        // {
        //     title: "type",
        //     dataIndex: "type",
        //     align: "center",
        //     key: "type",
        //     width: 80
        // },
        
        {
            title: "函数位置",
            dataIndex: "func_position",
            align: "center",
            key: "func_position",
            width: 250
        },
        {
                title: "操作",
                dataIndex: "action",
                align: "center",
                fixed: "right",
                width: 170,
                customRender: (row) => {
                    const editBtn = h(
                        Button,
                        {
                            type: "text",
                            onClick: () => {
                                selectedRowKeys.value = [row.record.id];
                                editData.func_position = row.record.func_position;
                                modal_edit_visible.value = true;
                            }
                        },
                        { default: () => "修改" }
                    );
                    const deleteBtn = h(
                        Popconfirm,
                        {
                            title: "请确认是否要删除?",
                            oktitle: "确认删除",
                            canceltitle: "取消",
                            onConfirm: () => {
                                deletebtn([row.record.id])
                            }
                        },
                        {
                            default: () =>
                                h(
                                    Button,
                                    {
                                        type: "text",
                                        danger: true
                                    },
                                    { default: () => "删除" }
                                )
                        }
                    );
                    return h(Space, { size: 2 }, { default: () => [deleteBtn] });
                }
            }
    ]
    
    
    const pagePotions = reactive({
            total: 0,
            page: 1,
            size: 10,
            pageSizeOptions: ["10", "20", "30", "40", "50", "100"]
        });
        const searchFieldOptions = [
            { label: "domain", value: "domain" },
            { label: "url", value: "url" },
        ];
    const searchForm = reactive({
        field_name: "domain",
        field_value: "",
        page: computed(() => {
            return pagePotions.page;
        }),
        limit: computed(() => {
            return pagePotions.size;
        }),
        sort_name: "id",
        sort_order: "desc"
    });
    
    const search = ()=>{
        if(selectedRowKeys.value.length>0){
            message.warning("搜索时，不能有选中的项，正在重新刷新页面")
            setTimeout(() => {
                window.location.reload()
            }, 1000)
            return
        }
        tableLoading.value = true;
        getMaterial(searchForm).then(res => {
            const data = res.data
            if(res.status === 200){
                tableData.value = data.data
                pagePotions.total = data.count
            }
            tableLoading.value = false;
        }).catch((err) => {
            tableLoading.value = false;
            message.error("获取数据失败");
        });
    }
    
    search();
    

    const handleTableChange = (pag: any, filters: any, sorter: any)=>{
        if (sorter.order) {
            searchForm.sort_order = sorter.order.slice(0, sorter.order.length - 3);
            searchForm.sort_name = sorter.field;
        } else {
            searchForm.sort_order = "";
        }
        search();
    }
    
    const pageChange = (page: number) => {
        pagePotions.page = page;
        selectedRowKeys.value = [];
        search();
    };
    
    
    const handleOk = () => {
        modal_visible.value = false;
        if (selectedRowKeys.value.length === 0) {
            message.error("请选择任务列表");
            return;
        }
        deletebtn(selectedRowKeys.value);
    }
    
    const fn_search = () => {
        pagePotions.page = 1;
        pagePotions.size = 10;
        searchForm.sort_name = "id";
        searchForm.sort_order = "desc";
        search();
    }
    
    const deletebtn =(ids:number[])=>{
        tableLoading.value = true;
        deltetMaterial(ids).then(res => {
            if(res.status === 200){
                message.success("删除成功");
                search();
                tableLoading.value = false;
            }
        }).catch((err) => {
            tableLoading.value = false;
            message.error(err.message);
        });
    }

    const addData = reactive({
        type: "",
        url: "",
        domain: "",
        func_position: ""
    })
    
    const addOk = () => {
        modal_add_visible.value = false;
        if (addData.type === "" || addData.url === "" || addData.domain === "" || addData.func_position === "") {
            message.error("请填写完整信息");
            return;
        }
        addMaterial(addData).then(res => {
            if(res.status === 200){
                message.success("添加成功");
                search();
            }
        }).catch((err) => {
            message.error(err.message);
        });
    }
    const editData = reactive({
        func_position: ""

    })
    const editOk = () => {
        const data = {
            ids: selectedRowKeys.value,
            body:{
                func_position: editData.func_position
            }
        }
        editMaterial(data).then(res=>{
            if(res.status === 200){
                message.success("修改成功");
                search();
            }
        }).catch((err) => {
            message.error(err.message);
        });

    }
    
    

    </script>
    
    <style lang="scss" scoped>
    
    </style>